# -*- coding: utf-8 -*-
"""
AI智能水面垃圾检测系统 - 主界面UI设计
功能：提供现代化的用户界面，支持图片、视频、实时检测等功能
作者：EcoAI Labs
版本：2.0
"""

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    """
    主窗口UI类 - 负责创建和配置所有界面元素
    采用现代化设计风格，支持响应式布局
    """

    def setupUi(self, MainWindow):
        """
        设置主窗口UI界面
        Args:
            MainWindow: 主窗口对象
        """
        # ===========================================
        # 1. 主窗口基础设置
        # ===========================================
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(2400, 1800)
        MainWindow.setMinimumSize(QtCore.QSize(1600, 960))

        # 统一字体族设置 - 优先使用现代字体
        self.base_font_family = "Microsoft YaHei UI, Segoe UI, Arial"

        # 设置现代窗口属性和图标
        self.setup_modern_window_properties(MainWindow)
        self._setup_window_icon(MainWindow)

        # ===========================================
        # 2. 创建中央组件和整体布局
        # ===========================================
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # 整体垂直布局 - 合理的边距和间距
        overall_layout = QtWidgets.QVBoxLayout(self.centralwidget)
        overall_layout.setContentsMargins(25, 25, 25, 25)
        overall_layout.setSpacing(25)

        # ===========================================
        # 3. 创建头部标题区域
        # ===========================================
        self._create_header_section(overall_layout)

        # ===========================================
        # 4. 创建主内容区域（左右布局）
        # ===========================================
        main_content_layout = QtWidgets.QHBoxLayout()
        main_content_layout.setSpacing(25)

        # 创建左侧面板（控制面板）
        left_panel_widget = self._create_left_panel()

        # 创建右侧面板（显示和统计面板）
        right_panel_widget = self._create_right_panel()

        # 添加到主内容布局（左侧1:右侧4的比例）
        main_content_layout.addWidget(left_panel_widget, 1)
        main_content_layout.addWidget(right_panel_widget, 4)

        # ===========================================
        # 5. 完成布局组装和状态栏设置
        # ===========================================
        overall_layout.addLayout(main_content_layout)
        MainWindow.setCentralWidget(self.centralwidget)

        # 创建状态栏
        self._create_status_bar(MainWindow)

        # 设置文本内容和信号连接
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def _setup_window_icon(self, MainWindow):
        """
        设置窗口图标
        Args:
            MainWindow: 主窗口对象
        """
        icon = QtGui.QIcon()
        try:
            icon.addPixmap(
                QtGui.QPixmap("UIProgram/ui_imgs/icons/目标检测.png"),
                QtGui.QIcon.Normal,
                QtGui.QIcon.Off
            )
            MainWindow.setWindowIcon(icon)
        except Exception as e:
            print(f"窗口图标设置失败: {e}")

    def _create_font(self, size, bold=False, italic=False):
        """
        创建标准化字体对象 - 减少重复代码
        Args:
            size: 字体大小
            bold: 是否加粗
            italic: 是否斜体
        Returns:
            QtGui.QFont: 配置好的字体对象
        """
        font = QtGui.QFont()
        font.setFamily(self.base_font_family)
        font.setPointSize(size)
        font.setBold(bold)
        font.setItalic(italic)
        return font

    def _create_header_section(self, parent_layout):
        """
        创建头部标题区域 - 重新调整布局结构
        Args:
            parent_layout: 父布局对象
        """
        # 头部容器设置
        self.header_widget = QtWidgets.QWidget()
        self.header_widget.setObjectName("header_widget")
        self.header_widget.setFixedHeight(250)

        # 头部水平布局
        header_layout = QtWidgets.QHBoxLayout(self.header_widget)
        header_layout.setContentsMargins(50, 40, 50, 40)
        header_layout.setSpacing(30)

        # ✅ 左侧标题组 - 简化内容，只保留主标题和描述
        left_title_widget = QtWidgets.QWidget()
        left_title_layout = QtWidgets.QVBoxLayout(left_title_widget)
        left_title_layout.setContentsMargins(0, 20, 0, 20)
        left_title_layout.setSpacing(25)  # 增加间距

        # ✅ 主标题 - 保持在左侧
        self.label_3 = QtWidgets.QLabel()
        self.label_3.setObjectName("label_3")
        self.label_3.setFont(self._create_font(30, bold=True))
        self.label_3.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.label_3.setMinimumHeight(60)
        self.label_3.setMaximumHeight(60)

        # ✅ 描述信息 - 保持在左侧
        self.extra_desc = QtWidgets.QLabel()
        self.extra_desc.setObjectName("extra_desc")
        self.extra_desc.setText("🚀 利用YOLOv8实现实时水面垃圾识别，助力生态保护")
        self.extra_desc.setFont(self._create_font(12, italic=True))
        self.extra_desc.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.extra_desc.setMinimumHeight(35)
        self.extra_desc.setMaximumHeight(35)
        self.extra_desc.setContentsMargins(0, 5, 0, 5)

        # 添加到左侧布局
        left_title_layout.addWidget(self.label_3)
        left_title_layout.addWidget(self.extra_desc)
        left_title_layout.addStretch()  # 底部弹性空间

        # ✅ 右侧标识区域 - 重新组织内容
        right_title_widget = QtWidgets.QWidget()
        right_title_layout = QtWidgets.QVBoxLayout(right_title_widget)
        right_title_layout.setContentsMargins(20, 20, 0, 20)
        right_title_layout.setSpacing(15)

        # ✅ 竞赛名称 - 从左侧移到右侧
        self.label_2 = QtWidgets.QLabel()
        self.label_2.setObjectName("label_2")
        self.label_2.setFont(self._create_font(14))  # 稍微减小字体
        self.label_2.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        self.label_2.setMinimumHeight(40)
        self.label_2.setMaximumHeight(40)
        self.label_2.setContentsMargins(0, 5, 0, 5)

        # ✅ 专项赛道信息 - 保持在右侧
        self.label_12 = QtWidgets.QLabel()
        self.label_12.setObjectName("label_12")
        self.label_12.setFont(self._create_font(16, bold=True))
        self.label_12.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        self.label_12.setMinimumHeight(40)
        self.label_12.setMaximumHeight(40)

        # ✅ 移除extra_info标签（不再需要"大学生创新竞赛作品"）
        # self.extra_info 这行删除了

        # 添加到右侧布局
        right_title_layout.addStretch(1)  # 顶部弹性空间
        right_title_layout.addWidget(self.label_2)  # 竞赛名称
        right_title_layout.addWidget(self.label_12)  # 专项赛道
        right_title_layout.addStretch(1)  # 底部弹性空间

        # 组装头部布局 - 调整比例
        header_layout.addWidget(left_title_widget, 6)  # 左侧占6份
        header_layout.addStretch(1)  # 中间弹性空间1份
        header_layout.addWidget(right_title_widget, 4)  # 右侧占4份（增加空间容纳更多文字）

        parent_layout.addWidget(self.header_widget)

    def _create_left_panel(self):
        """
        创建左侧控制面板
        Returns:
            QtWidgets.QWidget: 左侧面板组件
        """
        left_panel_widget = QtWidgets.QWidget()
        left_panel_layout = QtWidgets.QVBoxLayout(left_panel_widget)
        left_panel_layout.setContentsMargins(0, 0, 0, 0)
        left_panel_layout.setSpacing(25)

        # 创建各个功能组
        control_group = self._create_control_buttons_group()
        params_group = self._create_smart_params_group()
        results_group = self._create_results_analysis_group()

        # 添加到左侧面板
        left_panel_layout.addWidget(control_group)
        left_panel_layout.addWidget(params_group)
        left_panel_layout.addWidget(results_group)
        left_panel_layout.addStretch()  # 底部弹性空间

        return left_panel_widget

    def _create_control_buttons_group(self):
        """
        创建智能操作控制台按钮组
        Returns:
            QtWidgets.QGroupBox: 按钮组组件
        """
        self.groupBox_4 = QtWidgets.QGroupBox()
        self.groupBox_4.setObjectName("groupBox_4")
        self.groupBox_4.setFont(self._create_font(15, bold=True))
        self.groupBox_4.setMinimumHeight(320)  # 确保足够高度

        # 按钮布局 - 3行2列网格
        buttons_layout = QtWidgets.QGridLayout(self.groupBox_4)
        buttons_layout.setContentsMargins(25, 45, 25, 25)
        buttons_layout.setVerticalSpacing(20)  # 垂直间距
        buttons_layout.setHorizontalSpacing(18)  # 水平间距

        # 创建按钮字典和统一样式
        button_font = self._create_font(13, bold=True)
        self.buttons = {
            "PicBtn": QtWidgets.QPushButton(),
            "FilesBtn": QtWidgets.QPushButton(),
            "VideoBtn": QtWidgets.QPushButton(),
            "CapBtn": QtWidgets.QPushButton(),
            "SaveBtn": QtWidgets.QPushButton(),
            "ExitBtn": QtWidgets.QPushButton()
        }

        # 配置所有按钮的通用属性
        for name, btn in self.buttons.items():
            btn.setObjectName(name)
            btn.setFont(button_font)
            btn.setMinimumHeight(60)  # 增加按钮高度

        # 按钮网格布局
        buttons_layout.addWidget(self.buttons["PicBtn"], 0, 0)
        buttons_layout.addWidget(self.buttons["FilesBtn"], 0, 1)
        buttons_layout.addWidget(self.buttons["VideoBtn"], 1, 0)
        buttons_layout.addWidget(self.buttons["CapBtn"], 1, 1)
        buttons_layout.addWidget(self.buttons["SaveBtn"], 2, 0)
        buttons_layout.addWidget(self.buttons["ExitBtn"], 2, 1)

        return self.groupBox_4

    def _create_smart_params_group(self):
        """
        ✅ 创建智能检测参数配置组 - 使用VBox布局增加行间距
        Returns:
            QtWidgets.QGroupBox: 参数配置组组件
        """
        self.groupBox = QtWidgets.QGroupBox()
        self.groupBox.setObjectName("groupBox")
        self.groupBox.setFont(self._create_font(15, bold=True))
        self.groupBox.setMinimumHeight(240)  # 增加最小高度

        # ✅ 使用垂直布局替代网格布局，便于控制行间距
        params_main_layout = QtWidgets.QVBoxLayout(self.groupBox)
        params_main_layout.setContentsMargins(25, 45, 25, 25)
        params_main_layout.setSpacing(20)  # 主要的行间距

        # 创建参数行的通用字体
        label_font = self._create_font(12)
        spinbox_font = self._create_font(12)

        # ✅ 第一行：置信度阈值
        conf_row_widget = QtWidgets.QWidget()
        conf_row_layout = QtWidgets.QHBoxLayout(conf_row_widget)
        conf_row_layout.setContentsMargins(0, 0, 0, 0)
        conf_row_layout.setSpacing(15)

        self.label_14 = QtWidgets.QLabel()
        self.label_14.setObjectName("label_14")
        self.label_14.setFont(label_font)
        self.label_14.setMinimumHeight(40)

        self.doubleSpinBox = QtWidgets.QDoubleSpinBox()
        self.doubleSpinBox.setObjectName("doubleSpinBox")
        self.doubleSpinBox.setFont(spinbox_font)
        self.doubleSpinBox.setMinimumHeight(40)
        self.doubleSpinBox.setDecimals(2)
        self.doubleSpinBox.setMinimum(0.0)
        self.doubleSpinBox.setMaximum(1.0)
        self.doubleSpinBox.setSingleStep(0.01)
        self.doubleSpinBox.setValue(0.5)

        conf_row_layout.addWidget(self.label_14)
        conf_row_layout.addWidget(self.doubleSpinBox, 1)
        conf_row_layout.addStretch(1)  # 右侧弹性空间

        # ✅ 第二行：IoU阈值
        iou_row_widget = QtWidgets.QWidget()
        iou_row_layout = QtWidgets.QHBoxLayout(iou_row_widget)
        iou_row_layout.setContentsMargins(0, 0, 0, 0)
        iou_row_layout.setSpacing(15)

        self.label_15 = QtWidgets.QLabel()
        self.label_15.setObjectName("label_15")
        self.label_15.setFont(label_font)
        self.label_15.setMinimumHeight(40)

        self.doubleSpinBox_2 = QtWidgets.QDoubleSpinBox()
        self.doubleSpinBox_2.setObjectName("doubleSpinBox_2")
        self.doubleSpinBox_2.setFont(spinbox_font)
        self.doubleSpinBox_2.setMinimumHeight(40)
        self.doubleSpinBox_2.setDecimals(2)
        self.doubleSpinBox_2.setMinimum(0.0)
        self.doubleSpinBox_2.setMaximum(1.0)
        self.doubleSpinBox_2.setSingleStep(0.01)
        self.doubleSpinBox_2.setValue(0.45)

        iou_row_layout.addWidget(self.label_15)
        iou_row_layout.addWidget(self.doubleSpinBox_2, 1)
        iou_row_layout.addStretch(1)  # 右侧弹性空间

        # ✅ 第三行：复选框
        checkbox_row_widget = QtWidgets.QWidget()
        checkbox_row_layout = QtWidgets.QHBoxLayout(checkbox_row_widget)
        checkbox_row_layout.setContentsMargins(0, 0, 0, 0)

        self.checkBox = QtWidgets.QCheckBox()
        self.checkBox.setObjectName("checkBox")
        self.checkBox.setFont(self._create_font(12))
        self.checkBox.setMinimumHeight(40)
        self.checkBox.setChecked(True)

        checkbox_row_layout.addWidget(self.checkBox)
        checkbox_row_layout.addStretch()  # 右侧弹性空间

        # ✅ 将三行添加到主布局
        params_main_layout.addWidget(conf_row_widget)
        params_main_layout.addWidget(iou_row_widget)
        params_main_layout.addWidget(checkbox_row_widget)
        params_main_layout.addStretch()  # 底部弹性空间

        return self.groupBox

    def _create_results_analysis_group(self):
        """
        创建实时检测结果分析组
        Returns:
            QtWidgets.QGroupBox: 结果分析组组件
        """
        self.groupBox_2 = QtWidgets.QGroupBox()
        self.groupBox_2.setObjectName("groupBox_2")
        self.groupBox_2.setFont(self._create_font(15, bold=True))

        # 表单布局 - 更好的标签对齐
        results_layout = QtWidgets.QFormLayout(self.groupBox_2)
        results_layout.setContentsMargins(25, 45, 25, 25)
        results_layout.setVerticalSpacing(18)
        results_layout.setHorizontalSpacing(15)
        results_layout.setLabelAlignment(QtCore.Qt.AlignLeft)

        # 通用字体设置
        label_font = self._create_font(12)
        value_label_height = 35

        # 文件路径行
        path_label = QtWidgets.QLabel("📁 当前文件：")
        path_label.setFont(label_font)

        # 路径显示的堆叠组件
        self.pathStackedWidget = QtWidgets.QStackedWidget()
        line_edit_font = self._create_font(11)

        # 创建三种文件类型的输入框
        self.PiclineEdit = self._create_path_line_edit("PiclineEdit", "请选择图片文件...", line_edit_font)
        self.VideolineEdit = self._create_path_line_edit("VideolineEdit", "请选择视频文件...", line_edit_font)
        self.CaplineEdit = self._create_path_line_edit("CaplineEdit", "摄像头未开启...", line_edit_font)

        self.pathStackedWidget.addWidget(self.PiclineEdit)
        self.pathStackedWidget.addWidget(self.VideolineEdit)
        self.pathStackedWidget.addWidget(self.CaplineEdit)

        results_layout.addRow(path_label, self.pathStackedWidget)

        # 检测用时
        self.label_10 = QtWidgets.QLabel()
        self.label_10.setObjectName("label_10")
        self.label_10.setFont(label_font)
        self.time_lb = self._create_value_label("time_lb", label_font, value_label_height)
        results_layout.addRow(self.label_10, self.time_lb)

        # 目标数量
        self.label = QtWidgets.QLabel()
        self.label.setObjectName("label")
        self.label.setFont(label_font)
        self.label_nums = self._create_value_label("label_nums", label_font, value_label_height)
        results_layout.addRow(self.label, self.label_nums)

        # 目标选择下拉框
        self.label_5 = QtWidgets.QLabel()
        self.label_5.setObjectName("label_5")
        self.label_5.setFont(label_font)
        self.comboBox = QtWidgets.QComboBox()
        self.comboBox.setObjectName("comboBox")
        self.comboBox.setFont(self._create_font(12))
        self.comboBox.setMinimumHeight(40)
        results_layout.addRow(self.label_5, self.comboBox)

        # 类型显示
        self.label_13 = QtWidgets.QLabel()
        self.label_13.setObjectName("label_13")
        self.label_13.setFont(label_font)
        self.type_lb = self._create_value_label("type_lb", label_font, value_label_height)
        results_layout.addRow(self.label_13, self.type_lb)

        # 置信度显示
        self.label_11 = QtWidgets.QLabel()
        self.label_11.setObjectName("label_11")
        self.label_11.setFont(label_font)
        self.label_conf = self._create_value_label("label_conf", label_font, value_label_height)
        results_layout.addRow(self.label_11, self.label_conf)

        # 坐标信息组
        coord_group = self._create_coordinate_group()
        results_layout.addRow(coord_group)

        # 添加数据统计按钮
        self.stats_btn = QtWidgets.QPushButton()
        self.stats_btn.setObjectName("stats_btn")
        self.stats_btn.setText("📊 数据统计分析")
        self.stats_btn.setFont(self._create_font(12, bold=True))
        self.stats_btn.setMinimumHeight(45)
        self.stats_btn.setMaximumHeight(45)

        # 添加到布局的最后
        results_layout.addRow(self.stats_btn)

        return self.groupBox_2

    def _create_path_line_edit(self, name, placeholder, font):
        """
        创建路径输入框
        Args:
            name: 对象名称
            placeholder: 占位符文本
            font: 字体对象
        Returns:
            QtWidgets.QLineEdit: 配置好的输入框
        """
        line_edit = QtWidgets.QLineEdit()
        line_edit.setObjectName(name)
        line_edit.setPlaceholderText(placeholder)
        line_edit.setReadOnly(True)
        line_edit.setFont(font)
        line_edit.setMinimumHeight(38)
        return line_edit

    def _create_value_label(self, name, font, height):
        """
        创建数值显示标签
        Args:
            name: 对象名称
            font: 字体对象
            height: 最小高度
        Returns:
            QtWidgets.QLabel: 配置好的标签
        """
        label = QtWidgets.QLabel()
        label.setObjectName(name)
        label.setFont(font)
        label.setMinimumHeight(height)
        return label

    def _create_coordinate_group(self):
        """
        创建目标位置坐标组
        Returns:
            QtWidgets.QGroupBox: 坐标组组件
        """
        self.coord_group = QtWidgets.QGroupBox()
        self.coord_group.setObjectName("coord_group")
        self.coord_group.setFont(self._create_font(14, bold=True))

        # 坐标网格布局
        coord_layout = QtWidgets.QGridLayout(self.coord_group)
        coord_layout.setContentsMargins(20, 35, 20, 20)
        coord_layout.setSpacing(15)

        # 坐标标签字体
        coord_label_font = self._create_font(12)

        # 创建坐标标签和值标签
        coord_labels = [
            ("label_6", "label_xmin"),
            ("label_8", "label_ymin"),
            ("label_7", "label_xmax"),
            ("label_9", "label_ymax")
        ]

        for i, (label_name, value_name) in enumerate(coord_labels):
            # 标签
            label = QtWidgets.QLabel()
            label.setObjectName(label_name)
            label.setFont(coord_label_font)
            label.setMinimumHeight(30)
            setattr(self, label_name, label)

            # 值标签
            value_label = QtWidgets.QLabel()
            value_label.setObjectName(value_name)
            value_label.setFont(coord_label_font)
            value_label.setMinimumHeight(30)
            setattr(self, value_name, value_label)

            # 布局位置
            row = i // 2
            col_offset = (i % 2) * 2
            coord_layout.addWidget(label, row, col_offset)
            coord_layout.addWidget(value_label, row, col_offset + 1)

        return self.coord_group

    def _create_right_panel(self):
        """
        创建右侧显示面板
        Returns:
            QtWidgets.QWidget: 右侧面板组件
        """
        right_panel_widget = QtWidgets.QWidget()
        right_panel_layout = QtWidgets.QVBoxLayout(right_panel_widget)
        right_panel_layout.setContentsMargins(0, 0, 0, 0)
        right_panel_layout.setSpacing(25)

        # 创建显示区域和统计表格
        display_group = self._create_display_group()
        table_group = self._create_statistics_table_group()

        # 添加到右侧面板（显示区域占4份，表格占2份）
        right_panel_layout.addWidget(display_group, 4)
        right_panel_layout.addWidget(table_group, 2)

        return right_panel_widget

    def _create_display_group(self):
        """
        创建智能检测显示区域
        Returns:
            QtWidgets.QGroupBox: 显示区域组件
        """
        self.display_group = QtWidgets.QGroupBox()
        self.display_group.setObjectName("display_group")
        self.display_group.setFont(self._create_font(15, bold=True))

        # 显示区域布局
        display_layout = QtWidgets.QVBoxLayout(self.display_group)
        display_layout.setContentsMargins(25, 45, 25, 25)
        display_layout.setSpacing(20)

        # 主显示标签
        self.label_show = QtWidgets.QLabel()
        self.label_show.setObjectName("label_show")
        self.label_show.setAlignment(QtCore.Qt.AlignCenter)
        self.label_show.setMinimumHeight(400)  # 确保足够的显示区域

        display_layout.addWidget(self.label_show)

        return self.display_group

    def _create_statistics_table_group(self):
        """
        创建检测数据统计表格组
        Returns:
            QtWidgets.QGroupBox: 统计表格组组件
        """
        self.groupBox_3 = QtWidgets.QGroupBox()
        self.groupBox_3.setObjectName("groupBox_3")
        self.groupBox_3.setFont(self._create_font(15, bold=True))

        # 表格布局
        table_layout = QtWidgets.QVBoxLayout(self.groupBox_3)
        table_layout.setContentsMargins(25, 45, 25, 25)
        table_layout.setSpacing(15)

        # 创建表格
        self.tableWidget = QtWidgets.QTableWidget()
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(5)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setFont(self._create_font(11))
        self.tableWidget.setMinimumHeight(200)  # 确保表格最小高度

        # 设置表头
        headers = ["序号", "文件路径", "检测类别", "置信度", "坐标位置"]
        header_font = self._create_font(12, bold=True)

        for i, header in enumerate(headers):
            item = QtWidgets.QTableWidgetItem()
            item.setText(header)
            item.setFont(header_font)
            self.tableWidget.setHorizontalHeaderItem(i, item)

        # ✅ 优化表格列宽设置 - 修复文件路径列过宽问题
        header_view = self.tableWidget.horizontalHeader()
        header_view.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)  # 序号列 - 自适应
        header_view.setSectionResizeMode(1, QtWidgets.QHeaderView.Interactive)  # 文件路径列 - 可调整
        header_view.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)  # 检测类别列 - 自适应
        header_view.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)  # 置信度列 - 自适应
        header_view.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)  # 坐标列 - 填充剩余空间

        # 设置初始列宽
        self.tableWidget.setColumnWidth(0, 60)  # 序号列 - 窄一些
        self.tableWidget.setColumnWidth(1, 200)  # 文件路径列 - 限制宽度
        self.tableWidget.setColumnWidth(2, 100)  # 检测类别列 - 适中
        self.tableWidget.setColumnWidth(3, 80)  # 置信度列 - 较窄

        # 表格属性设置
        header_view.setMinimumSectionSize(50)
        self.tableWidget.setAlternatingRowColors(True)  # 启用隔行换色
        self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.tableWidget.verticalHeader().setVisible(False)

        table_layout.addWidget(self.tableWidget)

        return self.groupBox_3

    def _create_status_bar(self, MainWindow):
        """
        创建状态栏
        Args:
            MainWindow: 主窗口对象
        """
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        self.statusbar.setFont(self._create_font(10))
        MainWindow.setStatusBar(self.statusbar)

    def retranslateUi(self, MainWindow):
        """
        设置所有UI元素的文本内容
        Args:
            MainWindow: 主窗口对象
        """
        _translate = QtCore.QCoreApplication.translate

        # ===========================================
        # 主窗口和头部标题设置
        # ===========================================
        MainWindow.setWindowTitle(_translate("MainWindow", "🌊 AI智能水面垃圾检测系统 - 生态环保·AI赋能"))

        self.label_3.setText(_translate("MainWindow", "🌊 AI智能水面垃圾检测系统"))
        self.label_2.setText(_translate("MainWindow", "🏛️ 2025全国大学生数字媒体科技作品竞赛"))
        self.label_12.setText(_translate("MainWindow", "🎯 生态环保·AI赋能专项赛道"))

        # ===========================================
        # 控制按钮文本设置
        # ===========================================
        self.groupBox_4.setTitle(_translate("MainWindow", "🎮 智能操作控制台"))

        button_texts = {
            "PicBtn": "🖼️ 图片检测",
            "FilesBtn": "📁 批量检测",
            "VideoBtn": "🎥 视频检测",
            "CapBtn": "📷 实时检测",
            "SaveBtn": "💾 保存结果",
            "ExitBtn": "🚪 退出系统"
        }

        for btn_name, text in button_texts.items():
            self.buttons[btn_name].setText(_translate("MainWindow", text))

        # ===========================================
        # 参数配置区域文本设置
        # ===========================================
        self.groupBox.setTitle(_translate("MainWindow", "⚙️ 智能检测参数配置"))
        self.label_14.setText(_translate("MainWindow", "🎯 置信度阈值："))
        self.label_15.setText(_translate("MainWindow", "🔄 交并比阈值："))
        self.checkBox.setText(_translate("MainWindow", "🏷️ 显示标签名称与置信度"))

        # ===========================================
        # 结果分析区域文本设置
        # ===========================================
        self.groupBox_2.setTitle(_translate("MainWindow", "📊 实时检测结果分析"))

        # 基础检测信息
        self.label_10.setText(_translate("MainWindow", "⏱️ 检测用时："))
        self.label.setText(_translate("MainWindow", "🎯 目标数量："))
        self.label_5.setText(_translate("MainWindow", "🎮 目标选择："))
        self.label_13.setText(_translate("MainWindow", "🏷️ 类型："))
        self.label_11.setText(_translate("MainWindow", "📈 置信度："))

        # 坐标信息
        self.coord_group.setTitle(_translate("MainWindow", "📍 目标位置坐标"))
        coordinate_labels = {
            "label_6": "X最小值：",
            "label_8": "Y最小值：",
            "label_7": "X最大值：",
            "label_9": "Y最大值："
        }

        for label_name, text in coordinate_labels.items():
            getattr(self, label_name).setText(_translate("MainWindow", text))

        # ===========================================
        # 显示和统计区域文本设置
        # ===========================================
        self.display_group.setTitle(_translate("MainWindow", "🖼️ 智能检测显示区域"))
        self.label_show.setText(_translate("MainWindow", "🎯 请选择图片、视频或开启摄像头开始检测"))

        self.groupBox_3.setTitle(_translate("MainWindow", "📈 检测数据统计表格"))

        # 设置状态栏默认信息
        self.statusbar.showMessage("🌟 系统就绪 - 请选择检测模式开始使用")

    def setup_modern_window_properties(self, MainWindow):
        """
        设置现代化窗口属性
        Args:
            MainWindow: 主窗口对象
        """
        try:
            # 设置窗口属性 - 现代化外观
            MainWindow.setWindowFlags(
                QtCore.Qt.Window |
                QtCore.Qt.WindowMinimizeButtonHint |
                QtCore.Qt.WindowMaximizeButtonHint |
                QtCore.Qt.WindowCloseButtonHint
            )

            # 启用窗口阴影效果（Windows平台）
            if hasattr(QtCore.Qt, 'WA_TranslucentBackground'):
                MainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground, False)

            # 设置窗口图标和标题栏样式
            MainWindow.setStyleSheet("""
                QMainWindow {
                    background-color: #f0f0f0;
                }
            """)

            print("✅ 现代化窗口属性设置完成")

        except Exception as e:
            print(f"⚠️ 现代化窗口属性设置失败: {e}")

    def get_ui_components(self):
        """
        获取UI组件字典 - 便于外部访问
        Returns:
            dict: 包含所有主要UI组件的字典
        """
        return {
            # 控制按钮
            'buttons': self.buttons,

            # 参数控件
            'conf_spinbox': self.doubleSpinBox,
            'iou_spinbox': self.doubleSpinBox_2,
            'labels_checkbox': self.checkBox,
            'target_combobox': self.comboBox,

            # 显示控件
            'display_label': self.label_show,
            'path_stack': self.pathStackedWidget,
            'pic_edit': self.PiclineEdit,
            'video_edit': self.VideolineEdit,
            'cap_edit': self.CaplineEdit,

            # 结果显示标签
            'time_label': self.time_lb,
            'nums_label': self.label_nums,
            'type_label': self.type_lb,
            'conf_label': self.label_conf,
            'xmin_label': self.label_xmin,
            'ymin_label': self.label_ymin,
            'xmax_label': self.label_xmax,
            'ymax_label': self.label_ymax,

            # 表格组件
            'table_widget': self.tableWidget,

            # 状态栏
            'status_bar': self.statusbar
        }

    def set_responsive_layout(self):
        """
        设置响应式布局 - 根据窗口大小自动调整
        """
        try:
            # 获取主窗口尺寸
            main_widget = self.centralwidget.parent()
            if main_widget:
                width = main_widget.width()
                height = main_widget.height()

                # 根据窗口大小调整字体和间距
                if width < 1800:
                    # 小屏幕调整
                    self._adjust_for_small_screen()
                elif width > 2200:
                    # 大屏幕调整
                    self._adjust_for_large_screen()

                print(f"✅ 响应式布局调整完成 - 窗口尺寸: {width}x{height}")

        except Exception as e:
            print(f"⚠️ 响应式布局调整失败: {e}")

    def _adjust_for_small_screen(self):
        """小屏幕适配"""
        # 减小字体大小
        small_button_font = self._create_font(11, bold=True)
        for btn in self.buttons.values():
            btn.setFont(small_button_font)
            btn.setMinimumHeight(50)

        # 调整间距
        if hasattr(self, 'groupBox_4'):
            layout = self.groupBox_4.layout()
            if layout:
                layout.setSpacing(12)

    def _adjust_for_large_screen(self):
        """大屏幕适配"""
        # 增大字体大小
        large_button_font = self._create_font(15, bold=True)
        for btn in self.buttons.values():
            btn.setFont(large_button_font)
            btn.setMinimumHeight(70)

        # 调整间距
        if hasattr(self, 'groupBox_4'):
            layout = self.groupBox_4.layout()
            if layout:
                layout.setSpacing(25)

    def apply_accessibility_features(self):
        """
        应用无障碍功能 - 提升用户体验
        """
        try:
            # 设置Tab顺序 - 便于键盘导航
            tab_order = [
                self.buttons["PicBtn"],
                self.buttons["FilesBtn"],
                self.buttons["VideoBtn"],
                self.buttons["CapBtn"],
                self.doubleSpinBox,
                self.doubleSpinBox_2,
                self.checkBox,
                self.comboBox,
                self.buttons["SaveBtn"],
                self.buttons["ExitBtn"]
            ]

            # 设置Tab顺序
            for i in range(len(tab_order) - 1):
                QtWidgets.QWidget.setTabOrder(tab_order[i], tab_order[i + 1])

            # 设置快捷键
            self.buttons["PicBtn"].setShortcut("Ctrl+O")
            self.buttons["SaveBtn"].setShortcut("Ctrl+S")
            self.buttons["ExitBtn"].setShortcut("Alt+F4")

            # 设置工具提示已在MainProgram.py中处理

            print("✅ 无障碍功能应用完成")

        except Exception as e:
            print(f"⚠️ 无障碍功能应用失败: {e}")

    def update_ui_theme_compatibility(self):
        """
        更新UI主题兼容性 - 确保所有组件支持主题切换
        """
        try:
            # 为所有主要组件添加对象名称，便于CSS样式选择器
            component_names = {
                self.centralwidget: "central_widget",
                self.header_widget: "header_widget",
                self.display_group: "display_group",
                self.groupBox: "params_group",
                self.groupBox_2: "results_group",
                self.groupBox_3: "table_group",
                self.groupBox_4: "buttons_group",
                self.coord_group: "coord_group",
                self.tableWidget: "main_table",
                self.pathStackedWidget: "path_stack"
            }

            for component, name in component_names.items():
                if hasattr(component, 'setObjectName'):
                    component.setObjectName(name)

            # 确保所有标签都有合适的对象名称用于主题样式
            info_labels = [
                self.time_lb, self.label_nums, self.type_lb, self.label_conf,
                self.label_xmin, self.label_ymin, self.label_xmax, self.label_ymax
            ]

            for i, label in enumerate(info_labels):
                if not label.objectName():
                    label.setObjectName(f"info_label_{i}")

            print("✅ UI主题兼容性更新完成")

        except Exception as e:
            print(f"⚠️ UI主题兼容性更新失败: {e}")


# ===========================================
# 工具函数区域
# ===========================================

def create_modern_tooltip_style():
    """
    创建现代化工具提示样式
    Returns:
        str: CSS样式字符串
    """
    return """
    QToolTip {
        background-color: rgba(30, 30, 30, 0.9);
        color: white;
        border: 1px solid #555;
        border-radius: 8px;
        padding: 8px 12px;
        font-size: 11px;
        font-family: Microsoft YaHei UI, Segoe UI, Arial;
    }
    """

def validate_ui_components(ui_instance):
    """
    验证UI组件完整性
    Args:
        ui_instance: UI实例对象
    Returns:
        bool: 验证是否通过
    """
    required_components = [
        'buttons', 'doubleSpinBox', 'doubleSpinBox_2', 'checkBox',
        'label_show', 'tableWidget', 'pathStackedWidget', 'comboBox'
    ]

    missing_components = []
    for component in required_components:
        if not hasattr(ui_instance, component):
            missing_components.append(component)

    if missing_components:
        print(f"❌ UI组件验证失败，缺少组件: {missing_components}")
        return False

    print("✅ UI组件验证通过")
    return True


# ===========================================
# 使用示例和测试代码
# ===========================================

if __name__ == "__main__":
    """
    UI模块测试代码
    """
    import sys
    from PyQt5.QtWidgets import QApplication

    app = QApplication(sys.argv)

    # 创建主窗口和UI
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    # 验证UI组件
    validate_ui_components(ui)

    # 应用无障碍功能
    ui.apply_accessibility_features()

    # 更新主题兼容性
    ui.update_ui_theme_compatibility()

    # 显示窗口
    MainWindow.show()

    print("🎉 UI测试模式启动成功")
    print("📋 可用功能:")
    print("   - 响应式布局")
    print("   - 现代化按钮设计")
    print("   - 智能参数配置")
    print("   - 实时结果分析")
    print("   - 数据统计表格")
    print("   - 主题兼容性支持")

    sys.exit(app.exec_())

